package com.link.base.base.report.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.report.model.*;
import com.link.base.base.report.model.*;
import com.link.base.base.report.service.PortalReportService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.query.QueryParams;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.RedisConstants;
import com.link.core.util.RedisDataReportUtil;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 */
@Controller
@RequestMapping("/link/report")
public class ReportController {

    @Resource
    private PortalReportService portalReportService;

    /**
     * 客户类型报表
     */
    @RequestMapping(value = "/queryAccntTypeReport")
    @ResponseBody
    public Map<String, Object> queryAccntTypeReport(HttpSession session, @JsonParam QueryParams qps,
                                                    @JsonParam PortalAccountTypeReport acctTypeReport,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalAccountTypeReport> list = new ArrayList<PortalAccountTypeReport>();
        try {
            CoreUser user = UserUtil.getUser();
            //客户分类统计，安全性为自己
            acctTypeReport.setCreatedBy(user.getId());
            //新的报表取值逻辑，从redis中取。开始...
            int seconds = RedisDataReportUtil.getCfgCorpReportTimeProperty(
                    RedisConstants.SYS_PROPERTY_CORP_KEY + user.getLoginCorpId(), RedisDataReportUtil.REPORT_TIME_FIELD);
            int maxSeconds = 86400;
            if (seconds > 0 && seconds < maxSeconds) {
                //缓存时间大于0且小于一天，则执行缓存查询
                String key = RedisDataReportUtil.generateRedisKey(RedisDataReportUtil.USER_TYPE, user.getId().toString(), "queryAccntTypeReport");
                list = RedisDataReportUtil.getReportListDataFromRedis(key, PortalAccountTypeReport.class);
//              list = JSONArray.parseArray(RedisDataReportUtil.getReportStringDataFromRedis(key), PortalAccountTypeReport.class);
                if (null == list || list.size() == 0) {
                    list = portalReportService.queryAccntTypeReport(acctTypeReport);
                    RedisDataReportUtil.addReportListDataToRedis(key, list, seconds);
                }
            } else {
                list = portalReportService.queryAccntTypeReport(acctTypeReport);
            }
            //结束...
//          List<PortalAccountTypeReport> list = portalReportService.queryAccntTypeReport(acctTypeReport);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 客户类型报表
     */
    @RequestMapping(value = "/queryAccntTypeReportByPostn")
    @ResponseBody
    public Map<String, Object> queryAccntTypeReportByPostn(HttpSession session, @JsonParam QueryParams qps,
                                                           @JsonParam PortalAccountTypeReport acctTypeReport,
                                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalAccountTypeReport> list = new ArrayList<PortalAccountTypeReport>();
        try {
            list = portalReportService.queryAccntTypeReportByPostn(acctTypeReport);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryAccntTypeReport/export")
    @ResponseBody
    public Map<String, Object> queryAccntTypeReportExport(HttpSession session, @JsonParam QueryParams qps,
                                                          @JsonParam PortalAccountTypeReport acctTypeReport,
                                                          HttpServletRequest request, HttpServletResponse response) {
        //logger.info("导出列表...");
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            //客户分类统计，安全性为自己
            acctTypeReport.setCreatedBy(user.getId());
            qps.preDealSecurity(request);
            ExportWriter exportWriter = ExportFactory.newInstance(qps);
            while (!qps.getStopExport()) {
                exportWriter.wirteData(portalReportService.queryAccntTypeReport(acctTypeReport));
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 商机Top10报表
     */
    @RequestMapping(value = "/queryOptyTop10Report")
    @ResponseBody
    public Map<String, Object> queryOptyTop10Report(@JsonParam QueryParams qps, HttpSession session, @JsonParam PortalOptyTop10Report optyTop10Report,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalOptyTop10Report> list = new ArrayList<PortalOptyTop10Report>();
        try {
            CoreUser user = UserUtil.getUser();
            //我的商机top10安全性改为自己
            optyTop10Report.setCreatedBy(user.getId());

            //新的报表取值逻辑，从redis中取。开始...
            int seconds = RedisDataReportUtil.getCfgCorpReportTimeProperty(
                    RedisConstants.SYS_PROPERTY_CORP_KEY + user.getLoginCorpId(), RedisDataReportUtil.REPORT_TIME_FIELD);
            int maxSeconds = 86400;
            if (seconds > 0 && seconds < maxSeconds) {
                //缓存时间大于0且小于一天，则执行缓存查询
                String key = RedisDataReportUtil.generateRedisKey(RedisDataReportUtil.USER_TYPE, user.getId().toString(), "queryOptyTop10Report");
                list = RedisDataReportUtil.getReportListDataFromRedis(key, PortalOptyTop10Report.class);
                if (null == list || list.size() == 0) {
                    list = portalReportService.queryOptyTop10Report(optyTop10Report);
                    RedisDataReportUtil.addReportListDataToRedis(key, list, seconds);
                }
            } else {
                list = portalReportService.queryOptyTop10Report(optyTop10Report);
            }
            //结束...

//          List<PortalOptyTop10Report> list = portalReportService.queryOptyTop10Report(optyTop10Report);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryOptyTop10Report/export")
    @ResponseBody
    public Map<String, Object> queryOptyTop10ReportExport(@JsonParam QueryParams qps, HttpSession session,
                                                          @JsonParam PortalOptyTop10Report optyTop10Report,
                                                          HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryOptyTop10ReportExport")
                .withMessage("导出我的商机Top10...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            CoreUser user = UserUtil.getUser();
            //我的商机top10安全性改为自己
            optyTop10Report.setCreatedBy(user.getId());
            qps.preDealSecurity(request);
            ExportWriter exportWriter = ExportFactory.newInstance(qps);
            while (!qps.getStopExport()) {
                exportWriter.wirteData(portalReportService.queryOptyTop10Report(optyTop10Report));
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 商机阶段-销售漏斗
     */
    @RequestMapping(value = "/queryOptyStageReport", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryOptyStageReport(HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        PortalSearchText params = new PortalSearchText();
        try {
            List<PortalOptyStageReport> list = portalReportService.queryOptyStageReport(params);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 商机阶段-销售漏斗
     */
    @RequestMapping(value = "/queryReport", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryReport(QueryParams qps, HttpSession session,
                                           HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        PortalReportSearch rs = new PortalReportSearch();
        rs.setType(request.getParameter("type"));
        CoreUser login = UserUtil.getUser();
        rs.setLoginId(login.getId());

        //public List<SalesAmount> querySalesAmountReport(ReportSearch rs) throws Exception;
        String appInfo = "appInfo";
        String typeStr = "type";
        if (appInfo.equals(request.getParameter(typeStr))) {
            try {
                List<PortalBaseDataReport> list = portalReportService.queryReport(rs);
                result.put("success", true);
                result.put("rows", list);
            } catch (Exception e) {
                LCLogger.withException(e);
                result.put("success", false);
                result.put("message", e.getMessage());
            }
        }


        return result;
    }

    /**
     * 上周产品销售
     */
    @RequestMapping(value = "/queryCurrentWeekSales")
    @ResponseBody
    public Map<String, Object> queryCurrentWeekSales(@JsonParam QueryParams qps, @JsonParam PortalSalesAmount salesAmount,
                                                     HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryCurrentWeekSales")
                .withMessage("查询本周周销量列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<PortalSalesAmount> list = portalReportService.querySalesAmountReport(salesAmount);
            List<PortalSalesAmount> tempList = new ArrayList<PortalSalesAmount>();
            for (PortalSalesAmount record : list) {
                if ("L".equals(record.getType()) || "L" == record.getType()) {
                    tempList.add(record);
                }
            }
            list.removeAll(tempList);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryCurrentWeekSales/export")
    @ResponseBody
    public Map<String, Object> queryCurrentWeekSalesExport(@JsonParam QueryParams qps, @JsonParam PortalSalesAmount salesAmount, HttpSession session,
                                                           HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryCurrentWeekSalesExport")
                .withMessage("导出本周周销量列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalSalesAmount> list = null;
        try {
            qps.preDealSecurity(request);
            list = portalReportService.querySalesAmountReport(salesAmount);
            ExportWriter exportWriter = ExportFactory.newInstance(qps);
            List<PortalSalesAmount> tempList = new ArrayList<PortalSalesAmount>();
            for (PortalSalesAmount record : list) {
                if ("L".equals(record.getType()) || "L" == record.getType()) {
                    tempList.add(record);
                }
            }
            list.removeAll(tempList);
            while (!qps.getStopExport()) {
                exportWriter.wirteData(list);
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 上周产品销售
     */
    @RequestMapping(value = "/queryLastWeekSales")
    @ResponseBody
    public Map<String, Object> queryLastWeekSales(@JsonParam QueryParams qps, @JsonParam PortalSalesAmount salesAmount,
                                                  HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalSalesAmount> list = new ArrayList<PortalSalesAmount>();
        try {

            //新的报表取值逻辑，从redis中取。开始...
            CoreUser user = UserUtil.getUser();
            salesAmount.setCreatedBy(user.getId());
            int seconds = RedisDataReportUtil.getCfgCorpReportTimeProperty(
                    RedisConstants.SYS_PROPERTY_CORP_KEY + user.getLoginCorpId(), RedisDataReportUtil.REPORT_TIME_FIELD);
            int maxSeconds = 86400;
            if (seconds > 0 && seconds < maxSeconds) {
                //缓存时间大于0且小于一天，则执行缓存查询
                String key = RedisDataReportUtil.generateRedisKey(RedisDataReportUtil.USER_TYPE, user.getId().toString(), "queryLastWeekSales");
                list = RedisDataReportUtil.getReportListDataFromRedis(key, PortalSalesAmount.class);
                if (null == list || list.size() == 0) {
                    list = portalReportService.querySalesAmountReport(salesAmount);
                    List<PortalSalesAmount> tempList = new ArrayList<PortalSalesAmount>();
                    for (PortalSalesAmount record : list) {
                        if ("T".equals(record.getType()) || "T" == record.getType()) {
                            tempList.add(record);
                        }
                    }
                    list.removeAll(tempList);
                    RedisDataReportUtil.addReportListDataToRedis(key, list, seconds);
                }
            } else {
                list = portalReportService.querySalesAmountReport(salesAmount);
                List<PortalSalesAmount> tempList = new ArrayList<PortalSalesAmount>();
                for (PortalSalesAmount record : list) {
                    if ("T".equals(record.getType()) || "T" == record.getType()) {
                        tempList.add(record);
                    }
                }
                list.removeAll(tempList);
            }
            //结束...

//              List<PortalSalesAmount> list = portalReportService.querySalesAmountReport(salesAmount);
//              List<PortalSalesAmount> tempList = new ArrayList<PortalSalesAmount>();
//              for(PortalSalesAmount record : list){
//                  if( "T".equals(record.getType())|| "T"==record.getType() ){
//                      tempList.add(record);
//                  }
//              }
//              list.removeAll(tempList);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }


    /**
     * 查询年期间订单销售额
     */
    @RequestMapping(value = "/queryYearPeriodSales")
    @ResponseBody
    public Map<String, Object> queryYearPeriodSales(@JsonParam QueryParams qps, @JsonParam PortalSalesAmount salesAmount,
                                                  HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalSalesAmount> list = new ArrayList<PortalSalesAmount>();
        try {
            list = portalReportService.queryYearPeriodSales(salesAmount);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryLastWeekSales/export")
    @ResponseBody
    public Map<String, Object> queryLastWeekSalesExport(@JsonParam QueryParams qps, @JsonParam PortalSalesAmount salesAmount, HttpSession session,
                                                        HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryLastWeekSalesExport")
                .withMessage("导出上周周销量列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalSalesAmount> list = null;
        try {
            qps.preDealSecurity(request);
            list = portalReportService.querySalesAmountReport(salesAmount);
            ExportWriter exportWriter = ExportFactory.newInstance(qps);
            List<PortalSalesAmount> tempList = new ArrayList<PortalSalesAmount>();
            for (PortalSalesAmount record : list) {
                if ("T".equals(record.getType()) || "T" == record.getType()) {
                    tempList.add(record);
                }
            }
            list.removeAll(tempList);
            while (!qps.getStopExport()) {
                exportWriter.wirteData(list);
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 本月本月产品销售
     */
    @RequestMapping(value = "/queryCurrentMonthSales")
    @ResponseBody
    public Map<String, Object> queryCurrentMonthSales(@JsonParam QueryParams qps, @JsonParam PortalProductSalesReport prodSalesReport,
                                                      HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryCurrentMonthSales")
                .withMessage("查询本月月销量列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<PortalProductSalesReport> list = portalReportService.queryProductSalesReport(prodSalesReport);
            List<PortalProductSalesReport> tempList = new ArrayList<PortalProductSalesReport>();
            for (PortalProductSalesReport record : list) {
                if ("L".equals(record.getType()) || "L" == record.getType()) {
                    tempList.add(record);
                }
            }
            list.removeAll(tempList);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryCurrentMonthSales/export")
    @ResponseBody
    public Map<String, Object> queryCurrentMonthSalesExport(@JsonParam QueryParams qps,
                                                            @JsonParam PortalProductSalesReport prodSalesReport,
                                                            HttpSession session,
                                                            HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryCurrentMonthSales")
                .withMessage("导出本月月销量列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalProductSalesReport> list = null;
        try {
            qps.preDealSecurity(request);
            list = portalReportService.queryProductSalesReport(prodSalesReport);
            ExportWriter exportWriter = ExportFactory.newInstance(qps);
            List<PortalProductSalesReport> tempList = new ArrayList<PortalProductSalesReport>();
            for (PortalProductSalesReport record : list) {
                if ("L".equals(record.getType()) || "L" == record.getType()) {
                    tempList.add(record);
                }
            }
            list.removeAll(tempList);
            while (!qps.getStopExport()) {
                exportWriter.wirteData(list);
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 上月本月产品销售
     */
    @RequestMapping(value = "/queryLastMonthSales")
    @ResponseBody
    public Map<String, Object> queryLastMonthSales(@JsonParam QueryParams qps,
                                                   @JsonParam PortalProductSalesReport prodSalesReport,
                                                   HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryLastMonthSales")
                .withMessage("查询上月月销量列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<PortalProductSalesReport> list = portalReportService.queryProductSalesReport(prodSalesReport);
            List<PortalProductSalesReport> tempList = new ArrayList<PortalProductSalesReport>();
            for (PortalProductSalesReport record : list) {
                if ("T".equals(record.getType()) || "T" == record.getType()) {
                    tempList.add(record);
                }
            }
            list.removeAll(tempList);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/queryLastMonthSales/export")
    @ResponseBody
    public Map<String, Object> queryLastMonthSalesExport(@JsonParam QueryParams qps,
                                                         @JsonParam PortalProductSalesReport prodSalesReport, HttpSession session,
                                                         HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryLastMonthSales")
                .withMessage("导出上月月销量列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        List<PortalProductSalesReport> list = null;
        try {
            qps.preDealSecurity(request);
            list = portalReportService.queryProductSalesReport(prodSalesReport);
            ExportWriter exportWriter = ExportFactory.newInstance(qps);
            List<PortalProductSalesReport> tempList = new ArrayList<PortalProductSalesReport>();
            for (PortalProductSalesReport record : list) {
                if ("T".equals(record.getType()) || "T" == record.getType()) {
                    tempList.add(record);
                }
            }
            list.removeAll(tempList);
            while (!qps.getStopExport()) {
                exportWriter.wirteData(list);
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 消费者来源渠道构成
     */
    @RequestMapping(value = "/queryConsumerSourceConstitute")
    @ResponseBody
    public Map<String, Object> queryConsumerSourceConstitute(@JsonParam QueryParams qps,
                                                             @JsonParam PortalConsumerSourceConstitute consumerSourceConstitute,
                                                             HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryConsumerSourceConstitute")
                .withMessage("查询消费者来源渠道构成报表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            consumerSourceConstitute.setPageFlag(false);
            consumerSourceConstitute.setTotalFlag(false);
            List<PortalConsumerSourceConstitute> list = portalReportService.queryConsumerSourceConstitute(consumerSourceConstitute);
            result.put("success", true);
            result.put("rows", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 消费者来源渠道构成
     */
    @RequestMapping(value = "/queryConsumerSourceGrowth")
    @ResponseBody
    public Map<String, Object> queryConsumerSourceGrowth(@JsonParam QueryParams qps,
                                                         @JsonParam PortalConsumerSourceConstitute consumerSourceConstitute,
                                                         HttpSession session, HttpServletRequest request,
                                                         HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryConsumerSourceGrowth")
                .withMessage("查询消费者来源渠道增长量趋势报表...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            consumerSourceConstitute.setPageFlag(false);
            consumerSourceConstitute.setTotalFlag(false);
//              List<PortalConsumerSourceConstitute> list = portalReportService
//                  .queryConsumerSourceConstitute(consumerSourceConstitute);
            Map<String, Object> map = portalReportService.queryConsumerSourceGrowth(consumerSourceConstitute);
            result.put("success", true);
            result.put("map", map);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
}
